﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;
using PoemGame.Domain.GameAggregate;
using PoemGame.Domain.PlayerAggregate;
using PoemGame.Repository.MongoDb;

namespace ConsoleApp1
{
    internal class Utility
    {
        public static IConfigurationRoot GetConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

            IConfigurationRoot configuration = builder.Build();

            return configuration;
        }

        public static IMongoDatabase GetDb(IConfigurationRoot configuration)
        {
            var conn = configuration["MongoDb:Connection"];
            var dbName = configuration["MongoDb:DbName"];

            var client = new MongoClient(conn);
            //获得数据库、集合
            return  client.GetDatabase(dbName);
        }

        public static IServiceProvider GetService()
        {
            var conf = GetConfiguration();
            var services = new ServiceCollection();
            services.AddScoped<IMongoDatabase>(
                serviceProvider =>
                {
                    return GetDb(conf);
                }
                );
            services
                .AddScoped<IGameRepository, GameRepository>()
                .AddScoped<IPlayerRepository, PlayerRepository>();
        
            var serviceProvider = services.BuildServiceProvider();
            return serviceProvider;
        }
    }
}
